package per.wsj.paging;

import androidx.annotation.NonNull;
import androidx.paging.PageKeyedDataSource;

import java.util.List;

public class CustomPageDataSource extends PageKeyedDataSource<Integer, StudentModel> {

    private CustomRepository mCustomRepository;

    CustomPageDataSource(CustomRepository customRepository) {
        this.mCustomRepository = customRepository;
    }

    @Override
    public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, StudentModel> callback) {
        List<StudentModel> studentModels = mCustomRepository.getStudentsInit(params.requestedLoadSize);
        callback.onResult(studentModels, null, 1);
    }

    @Override
    public void loadBefore(@NonNull final LoadParams<Integer> params, @NonNull final LoadCallback<Integer, StudentModel> callback) {
        //模拟网络调用耗时操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                List<StudentModel> studentModels = mCustomRepository.getStudentsByPage(params.key, params.requestedLoadSize);
                callback.onResult(studentModels, params.key - 1);
            }
        }).start();
    }

    @Override
    public void loadAfter(@NonNull final LoadParams<Integer> params, @NonNull final LoadCallback<Integer, StudentModel> callback) {
        //模拟网络调用耗时操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                List<StudentModel> studentModels = mCustomRepository.getStudentsByPage(params.key, params.requestedLoadSize);
                if (studentModels != null) {
                    callback.onResult(studentModels, params.key + 1);
                }
            }
        }).start();
    }
}
